package com.example.service.Service;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.service.R;

public class BindService extends Fragment {
    private MyConn myConn = null;

    public BindService(){
        super(R.layout.bind_service);
    }

    public class MyConn implements ServiceConnection{
        public MusiceService2.MyBinder myBinder = null;
        @Override
        public void onServiceConnected(ComponentName name, IBinder service){
            myBinder = (MusiceService2.MyBinder)service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name){
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle saveInstanceState) {
        super.onViewCreated(view, saveInstanceState);

        Intent intent = new Intent(getActivity(), MusiceService2.class);
        getActivity().startService(intent);

        if(myConn == null){
            myConn = new MyConn();
            intent = new Intent(getActivity(), MusiceService2.class);
            getActivity().bindService(intent, myConn, 0);
        }

        Button playMusicButton = getView().findViewById(R.id.play);
        Button nextMusicButton = getView().findViewById(R.id.next);
        Button stopMusicButton = getView().findViewById(R.id.stop);

        playMusicButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(myConn.myBinder == null){
                    return;
                }
                myConn.myBinder.play();
            }
        });

        nextMusicButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(myConn.myBinder == null){
                    return;
                }
                myConn.myBinder.next();
            }
        });

        stopMusicButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(myConn.myBinder == null){
                    return;
                }
                myConn.myBinder.pause();
            }
        });
    }
}
